#define _CRT_SECURE_NO_WARNINGS
#include "Queue.h"

void QueueInit(struct Queue *q)
{
	assert(q);
	q->head = NULL;
	q->tail = NULL;
	q->size = 0;
}

QDataType QueuePop(struct Queue* q)
{
	assert(q);
	//assert(q->head);
	assert(!QueueEmpty(q));
	QNode* next = q->head->next;
	QDataType ret = q->head->data;
	free(q->head);
	q->head = next;
	if (next == NULL)
		q->tail = NULL;
	q->size--;
	return ret;
}

void QueuePush(struct Queue* q, QDataType x)
{
	assert(q);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;

	if (q->head == NULL)
	{
		q->head = newnode;
		q->tail = q->head;
	}
	else
	{
		q->tail->next = newnode;
		q->tail = newnode;
	}
	q->size++;
}

void QueueDestory(struct Queue* q)
{
	assert(q);
	while (q->head)
	{
		QNode*next = q->head->next;
		free(q->head);
		q->head = next;
	}
	q->head = NULL;
	q->tail = NULL;
	q->size = 0;

}

bool QueueEmpty(struct Queue* q)
{
	assert(q);
	//return (q->head == NULL) && (q->tail == NULL);
	return q->size == 0;
}

QDataType QueueFront(struct Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	return q->head->data;
}

QDataType QueueBack(struct Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	return q->tail->data;
}

int QueueSize(struct Queue* q)
{
	assert(q);
	return q->size;
}